package com.sym.nestscrollview;

import android.content.Context;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;

import androidx.annotation.NonNull;

/**
 * @author Administrator
 */
public class DragView extends View implements ViewTreeObserver.OnGlobalLayoutListener {

    private final static String TAG = "DragImageView";
    /**
     * 上下文
     */
    private Context mContext;
    /**
     * 启始位置
     */
    private int startY;
    /**
     * 停止位置
     */
    private int stopY;

    /**
     * 头部View,底部View,容器View
     */
    private View mTopView, mBottomView, mContainerView;
    /**
     * 底部View
     */
    private int mTopViewHeight, mTotalHeight;

    /**
     * 防止重复计算高度
     */
    private boolean mFlag;


    public DragView(Context context) {
        super(context);
        this.mContext = context;
    }

    public DragView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
    }

    public DragView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Log.i(TAG, "onDraw");

        //在默认 画布上绘制圆角矩形
        mPaint.reset();
        mPaint.setColor(Color.WHITE);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setAntiAlias(true);
        mPaint.setMaskFilter(mBlur);
        canvas.drawRoundRect(mOuterRectF, mOuterRadius, mOuterRadius, mPaint);

        int layerId = canvas.saveLayer(0, 0, mWidth, mHeight, null, Canvas.ALL_SAVE_FLAG);

        mPaint.reset();
        mPaint.setAntiAlias(true);
        mPaint.setColor(Color.WHITE);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));
        canvas.drawRect(mOuterRectF01, mPaint);
        canvas.restoreToCount(layerId);


        //上面的黑色按钮
        mPaint.reset();
        mPaint.setColor(Color.parseColor("#FF273344"));
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setAntiAlias(true);
        canvas.drawRoundRect(mRectF, mRadius, mRadius, mPaint);
    }

    Paint mPaint;
    RectF mRectF;
    int mRadius;
    int mOuterRadius;
    int mShadowLength;
    RectF mOuterRectF, mOuterRectF01;

    /**
     * 宽度
     */
    private int mWidth;

    /**
     * 高度
     */
    private int mHeight;

    /**
     * 阴影颜色
     */
    private int mBlurColor;

    private BlurMaskFilter mBlur;

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        Log.i(TAG, "onSizeChanged");
        mPaint = new Paint();

        mBlurColor = Color.parseColor("#0D0B2A71");
        mWidth = getMeasuredWidth();
        mHeight = getMeasuredHeight();
        int rectW = dip2px(getContext().getApplicationContext(), 32);
        int rectH = dip2px(getContext().getApplicationContext(), 2);
        mRadius = dip2px(getContext().getApplicationContext(), 1);
        mOuterRadius = dip2px(getContext().getApplicationContext(), 6);
        mShadowLength = dip2px(getContext().getApplicationContext(), 16);

        int startX = mWidth / 2 - rectW / 2;
        int startY = mHeight / 2 - rectH / 2;
        int endX = startX + rectW;
        int endY = startY + rectH;

        mOuterRectF = new RectF(0, 0, mWidth, mHeight);
        mOuterRectF01 = new RectF(0, mOuterRadius, mWidth, mHeight);
        mRectF = new RectF(startX, startY, endX, endY);
        mBlur = new BlurMaskFilter(mOuterRadius, BlurMaskFilter.Blur.SOLID);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                startY = (int) event.getRawY();
                break;
            case MotionEvent.ACTION_MOVE:
                stopY = (int) event.getRawY();
                int deltaY = stopY - startY;
                this.moveToPosition(deltaY);
                stopY = (int) event.getRawY();
                invalidate();
                break;
            case MotionEvent.ACTION_UP:
                deltaY = stopY - startY;
                mTopViewHeight = mTopViewHeight + deltaY;
                break;

            default:
                break;
        }
        return true;
    }

    /**
     * 注入头部和底部View
     *
     * @param topView    头部View
     * @param bottomView 底部View
     */
    public void injectView(View topView, View bottomView, View containerView) {

        this.mTopView = topView;
        this.mBottomView = bottomView;
        this.mContainerView = containerView;
        getViewTreeObserver().addOnGlobalLayoutListener(this);
    }

    /**
     * 滑动算法
     *
     * @param deltaY 手指滑动的距离
     */
    private void moveToPosition(int deltaY) {

        int scaledTouchSlop = ViewConfiguration.get(mContext.getApplicationContext()).getScaledTouchSlop() / 4;
        if (Math.abs(deltaY) < scaledTouchSlop) {
            return;
        }

        int height = mTopViewHeight + deltaY;
        if (height < 400 || height > 800) {
            return;
        }

        ViewGroup.LayoutParams layoutParams = mTopView.getLayoutParams();
        layoutParams.height = height;
        mTopView.setLayoutParams(layoutParams);

        layoutParams = mBottomView.getLayoutParams();
        layoutParams.height = mTotalHeight - height;
        mBottomView.setLayoutParams(layoutParams);
    }

    @Override
    public void onGlobalLayout() {

        if (!mFlag) {
            mFlag = true;
            int rootHeight = mContainerView.getMeasuredHeight();
            int dragViewHeight = getMeasuredHeight();

            int total = rootHeight - dragViewHeight;
            int height = total / 2;
            ViewGroup.LayoutParams layoutParams = mTopView.getLayoutParams();
            layoutParams.height = height;
            mTopView.setLayoutParams(layoutParams);

            layoutParams = mBottomView.getLayoutParams();
            layoutParams.height = height;
            mBottomView.setLayoutParams(layoutParams);

            this.mTotalHeight = total;
            this.mTopViewHeight = height;
        }
    }

    /**
     * dp 转 px
     *
     * @param context {@link Context}
     * @param dpValue {@code dpValue}
     * @return {@code pxValue}
     */
    public static int dip2px(@NonNull Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}
